package com.git.hui.yinshua.biz.order.schedule;

import com.git.hui.yinshua.biz.order.dao.repository.OrderRepository;
import com.git.hui.yinshua.biz.order.dao.repository.PtOrderRepository;
import com.git.hui.yinshua.biz.order.service.OrderService;
import com.git.hui.yinshua.biz.order.service.PtOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 订单相关定时器
 *
 * @author YiHui
 * @date 2024/7/5
 */
@Slf4j
@Service
public class OrderSchedule {
    @Autowired
    private PtOrderRepository ptOrderRepository;
    @Autowired
    private PtOrderService ptOrderService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderService orderService;

    /**
     * 定时关闭超时的拼团单
     */
    @Scheduled(fixedRate = 60_000)
    public void autoCloseOverTimePtOrder() {
        try {
            List<Integer> list = ptOrderRepository.queryOverTimedPtOrders();
            if (CollectionUtils.isEmpty(list)) {
                return;
            }

            for (Integer ptOrderId : list) {
                ptOrderService.autoClosePtOrder(ptOrderId);
            }
        } catch (Exception e) {
            log.error("自动关闭超时拼团订单异常:", e);
        }
    }


    /**
     * 自动关闭超时未支付的订单
     */
    @Scheduled(fixedRate = 60_000)
    public void autoCloseOverTimeOrder() {
        try {
            List<Long> list = orderRepository.queryOverTimeOrders();
            if (CollectionUtils.isEmpty(list)) {
                return;
            }

            list.forEach(orderId -> orderService.orderCancel(orderId));
        } catch (Exception e) {
            log.error("自动关闭超时拼团订单异常:", e);
        }
    }
}
